#include <QStackedWidget>

#include "contextmanager.h"

ContextManager::ContextManager(QObject *parent) :
    QObject(parent),
    m_stackedWidget(new QStackedWidget(0))
{
}

ContextManager::~ContextManager()
{
    delete m_stackedWidget;
    m_stackedWidget = 0;
}

void ContextManager::addContext(int uid)
{
    if (m_contexts.contains(uid))
        qWarning(QString("ContextManager: Already contains `%1`").arg(uid).toLocal8Bit());
    else {
        m_contexts.append(uid);
        emit currentChanged();
    }
}

QList<int> ContextManager::currentContext() const
{
    return m_contexts;
}

void ContextManager::removeContext(int uid)
{
    m_contexts.removeOne(uid);
}

//*************** gui
void ContextManager::addGuiContext(int uid, QWidget *w)
{
    if (m_guiContexts.contains(uid))
        qWarning(QString("ContextManager: Already contains gui:`%1`").arg(uid).toLocal8Bit());
    else {
        m_guiContexts.append(uid);
        m_stackedWidget->addWidget(w);
        if (m_stackedWidget->count() == 1) {
            m_currentGuiContext = uid;
            m_contexts.append(uid);
            emit currentChanged();
        }
    }
}

int ContextManager::currentGuiContext() const
{
    return m_guiContexts.value(m_stackedWidget->currentIndex(), 0);
}

void ContextManager::setGuiContext(int uid)
{
    QWidget *w = m_stackedWidget->widget(m_guiContexts.indexOf(uid));
    if (!w)
        qWarning(QString("ContextManager: Bad context `%1`").arg(uid).toLocal8Bit());
    else {
        if (w != m_stackedWidget->currentWidget()) {
            m_stackedWidget->setCurrentWidget(w);
            m_contexts.removeOne(m_currentGuiContext);
            m_contexts.append(uid);
            m_currentGuiContext = uid;
            emit currentChanged();
        }
    }
}

void ContextManager::removeGuiContext(int uid)
{
    int index = m_guiContexts.indexOf(uid);
    if (index != -1) {
        m_guiContexts.removeAt(index);
        m_stackedWidget->removeWidget(m_stackedWidget->widget(index));
        if (uid == m_currentGuiContext) {
            m_contexts.removeOne(uid);
            emit currentChanged();
        }
    } else
        qWarning(QString("ContextManager: Unknown context `%1`").arg(uid).toLocal8Bit());
}
